<?php

namespace Plugin\AdCloak\Controllers;

use app\model\Licenses;
use Beike\Admin\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Plugin\AdCloak\Models\AdCloakUrls;

class AdCloakController extends Controller
{


    public function cloakIndex(Request $request)
    {
        $plugin = app('plugin')->getPlugin('ad_cloak');
        $data   = [
            'name'        => '广告斗篷',
            'description' => $plugin->getLocaleDescription(),
        ];
        return view('AdCloak::admin.index', $data);
    }

    public function urls()
    {
        $urls = AdCloakUrls::query()->orderByDesc('sort')->paginate(perPage());
        return response()->json([
            'urls' => $urls,
        ]);
    }

    public function urls_save(Request $request)
    {
        $id = $request->id;
        if ($id && $id > 0) {
            $cloak = AdCloakUrls::query()->where('id', $id)->first();
            if (empty($cloak)) {
                throw new \Exception('链接数据不存在');
            }
        } else {
            $cloak = new AdCloakUrls();
        }
        $cloak->name     = $request->name;
        $cloak->url_from = $request->url_from;
        $cloak->url_to   = $request->url_to;
        $cloak->type     = $request->type;
        $cloak->sort     = $request->sort;
        if ($id && $id > 0) {
            $cloak->update();
        } else {
            $cloak->save();
        }
        return response()->json(['code' => 0]);
    }

    public function urls_del(Request $request)
    {
        $id = $request->id;
        if (!$id) {
            throw new \Exception('链接数据不存在');
        }
        $cloak = AdCloakUrls::query()->where('id', $id)->first();
        if (empty($cloak)) {
            throw new \Exception('链接数据不存在!');
        }
        $cloak->delete();
        return response()->json(['code' => 0]);
    }
}
